package com.stationpc.androidtvrecents

import android.app.AppOpsManager
import android.content.Context
import android.content.Intent
import android.graphics.Rect
import android.os.Bundle
import android.os.Process
import android.provider.Settings
import android.view.View
import androidx.activity.viewModels
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.RecyclerView
import com.stationpc.androidtvrecents.databinding.ActivityMainBinding

class MainActivity : FragmentActivity() {
    private lateinit var binding: ActivityMainBinding
    private val viewModel: RecentAppsViewModel by viewModels()
    private lateinit var adapter: RecentAppsAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        if (!isValidDevice()) {
            finish()
            return
        }

        if (!hasUsageStatsPermission()) {
            startActivity(Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS))
        }

        setupRecyclerView()
        observeRecentApps()
        handleIntent(intent)
    }

    private fun setupRecyclerView() {
        adapter = RecentAppsAdapter(
            context = this,
            onItemAction = { position, action ->
                when (action) {
                    Action.OPEN -> viewModel.openApp(position)
                    Action.CLOSE -> viewModel.removeApp(position)
                }
            },
            onFocusChange = { view, hasFocus ->
                TransitionHelper.animateScale(view, hasFocus)
            }
        )

        binding.recentAppsGrid.apply {
            this.adapter = this@MainActivity.adapter
            itemAnimator = RecentAppsAnimator()
            val spacing = resources.getDimensionPixelSize(R.dimen.banner_spacing)
            addItemDecoration(object : RecyclerView.ItemDecoration() {
                override fun getItemOffsets(
                    outRect: Rect,
                    view: View,
                    parent: RecyclerView,
                    state: RecyclerView.State
                ) {
                    outRect.left = spacing / 2
                    outRect.right = spacing / 2
                }
            })
        }
    }

    private fun observeRecentApps() {
        viewModel.recentApps.observe(this) { apps ->
            adapter.submitList(apps)
        }
    }

    private fun hasUsageStatsPermission(): Boolean {
        val appOps = getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager
        val mode = appOps.checkOpNoThrow(
            AppOpsManager.OPSTR_GET_USAGE_STATS,
            Process.myUid(),
            packageName
        )
        return mode == AppOpsManager.MODE_ALLOWED
    }

    private fun isValidDevice(): Boolean {
        return try {
            val systemPropertiesClass = Class.forName("android.os.SystemProperties")
            val getMethod = systemPropertiesClass.getMethod("get", String::class.java, String::class.java)
            val buildUser = getMethod.invoke(null, "ro.build.user", "") as String
            val productModel = getMethod.invoke(null, "ro.product.system.model", "") as String
            buildUser == "mo123" && productModel == "Station_M3"
        } catch (e: Exception) {
            false
        }
    }

    private fun handleIntent(intent: Intent) {
        when (intent.action) {
            Intent.ACTION_VIEW, Intent.ACTION_MAIN -> {
                viewModel.loadRecentApps()
            }
        }
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        handleIntent(intent)
    }

    override fun onResume() {
        super.onResume()
        viewModel.loadRecentApps()
    }
}
